import random
import time
import traceback
import uiautomation as auto
from .base_operations import WeChatBaseOperations, random_wait

class WeChatV4Operations(WeChatBaseOperations):
    
    def __init__(self, log_fun, phone_number, name, apply_msg, prefix, tag):
        super().__init__(log_fun, phone_number, name, apply_msg, prefix, tag)
        self.wechat_window_class_name = "mmui::MainWindow"
        self.sidebar_btns = ["更多", "收藏", "手机", "通讯录"]

    def click_sidebar_entry(self):
        return self._switch_to_chatlist()
    
    def click_add_friend_list_item(self, weixin_win):
        # 遍历所有ListItemControl
        list_items = []
        for control, _ in auto.WalkControl(weixin_win, maxDepth=10):
            if isinstance(control, auto.ListItemControl):
                list_items.append(control)

        second_item = list_items[1]
        print(f"点击第二个列表项: {second_item.Name}")
        second_item.Click()

    def add_friend(self):
        """V4加好友完整流程"""
        self._log("添加朋友")
        try:
            # 点击添加快捷操作按钮
            add_btn = auto.ButtonControl(Name="快捷操作")
            if not add_btn.Exists():
                return False
            self._human_click(add_btn)

            weixin_win = auto.WindowControl(Name="Weixin")
            if not weixin_win.Exists():
                return False
            
            # 点击弹出列表的添加朋友
            self.click_add_friend_list_item(weixin_win)

            add_friend_window = auto.WindowControl(Name="添加朋友")
            if not add_friend_window.Exists():
                return False
            
            # 输入手机号
            input_box = add_friend_window.EditControl(Name="搜索")
            if not input_box.Exists():
                return False
            self._human_click(input_box)
            self._human_type(input_box, self.phone_number)
            input_box.SendKeys("{Enter}")
            # 执行添加操作
            add_result = self._perform_add_action(add_friend_window)
            self._log("准备关闭添加朋友窗口")
            close_btn = add_friend_window.ButtonControl(Name="关闭", searchDepth=3)
            if close_btn.Exists():
                self._human_click(close_btn)
            return add_result
        except Exception as e:
            self._log(f"添加好友出错: {str(e)}")
            self._log(traceback.format_exc())
            return False

    def _check_search_result(self, phone_number):
        """检查搜索结果"""
        result_text = auto.TextControl(Name=f"搜索：{phone_number}")
        if not result_text.Exists():
            self._click_wechat_blank()
            return False
        self._human_click(result_text)
        return True

    def find_and_click_add_contact_button(self,add_friend_window):
        """在添加好友窗口中查找并点击"添加到通讯录"按钮"""
        # 定义按钮查找条件
        def is_add_contact_button(control):
            return (isinstance(control, auto.ButtonControl) and
                    "添加到通讯录" in control.Name)
        
        # 使用 WalkControl 遍历所有子控件
        for control, _ in auto.WalkControl(add_friend_window, maxDepth=10):
            if is_add_contact_button(control):
                print(f"找到按钮: {control.Name}")
                # 点击按钮
                self._human_click(control)
                print("已点击'添加到通讯录'按钮")
                return True
    
        print("未找到'添加到通讯录'按钮")
        return False
    def _perform_add_action(self, add_friend_window):
        """执行添加操作"""
        # 查找和点击添加到通讯录按钮
        time.sleep(2)

        # 添加到通讯录
        self._log("查找'添加到通讯录'按钮")
        add_contact_button = add_friend_window.ButtonControl(Name="添加到通讯录", searchDepth=15)
        if add_contact_button.Exists():
            self._human_click(add_contact_button)
            self._log("已点击'添加到通讯录'按钮")
            friend_request_window = auto.WindowControl(Name="申请添加朋友", searchDepth= 5)
            self._log("等待“申请添加朋友“窗口出现，请稍等...")
            if friend_request_window.Exists():
                self._log("已找到“申请添加朋友“窗口,开始填写申请信息")
                return self._send_friend_request(friend_request_window)
            else:   # 处理不需要申请直接通过的好友的情况
                self._log("没有找到“申请添加朋友“窗口,开始检查是否已经添加过该好友")
                if self._check_already_added(add_friend_window):
                    self._log("已添加过该用户")
                    return "已添加好友"


        # 检查是否已经添加了该用户
        self._log("begin _check_already_added")
        if self._check_already_added(add_friend_window):
            self._log("已添加过该用户")
            return "已添加好友"

        # 检查用户是否存在
        self._log("begin _check_user_not_exist")
        if self._check_user_not_exist(add_friend_window):
            self._log("账号不存在")
            return "账号不存在"

        return ""

    def _check_already_added(self, add_friend_window: auto.WindowControl):
        """检查是否已添加"""
        # remark = self._recursive_find_control(auto.GetForegroundControl(), auto.TextControl, "备注")
        remark = add_friend_window.ButtonControl(Name = "发消息", searchDepth=10)
        #print("这个名字是啥" + remark.Name)
        if remark.Exists():
            close_btn = add_friend_window.ButtonControl(Name="关闭", searchDepth=3)
            if close_btn.Exists():
                self._human_click(close_btn)
            return True
        return False

    def _check_user_not_exist(self, add_friend_window: auto.WindowControl):
        """检查用户是否存在"""
        not_found = add_friend_window.TextControl(Name = "无法找到该用户，请检查你填写的账号是否正确。", searchDepth=8)
        #not_found = self._recursive_find_control(auto.GetForegroundControl(), auto.TextControl, "无法找到该用户，请检查你填写的账号是否正确。")
        if not_found.Exists():
            print("这个名字是咩野" + not_found.Name)
            close_btn = add_friend_window.ButtonControl(Name="关闭", searchDepth=3)
            if close_btn.Exists():
                self._human_click(close_btn)
            return True
        return False

    def _send_friend_request(self, window: auto.WindowControl):
        """发送好友请求"""
        # window = auto.WindowControl(Name="申请添加朋友")
        # if not window.Exists():
        #     return False
        
        inputs = self._find_all_edit_controls(window)
        if len(inputs) < 2:
            return False

        # 填写申请信息
        self._human_click(inputs[0])
        inputs[0].SendKeys('{Ctrl}{A}{Delete}')
        self._human_type(inputs[0], self.apply_msg.format(name=self.name))

        # 填写备注
        self._human_click(inputs[1])
        inputs[1].SendKeys('{Ctrl}{A}{Delete}')
        self._human_type(inputs[1], self.prefix + self.name)

        # 填写标签
        if self.tag != "":
            tag_btn = window.ButtonControl(Name="修改标签")
            if tag_btn.Exists():
                tag_arr = self.tag.split("，")
                for tag in tag_arr:  
                    self._human_click(tag_btn)
                    search = window.EditControl(Name="搜索")
                    if search.Exists():   
                        self._human_type(search, tag)
                        list_item = window.ListItemControl(SubName=tag)
                        if list_item.Exists():
                            self._log("点击标签项目")
                            self._human_click(list_item)
                        self._human_click(tag_btn) # 最后点一下消除下拉框
                
            

                   
        time.sleep(5)
        # 点击确定
        confirm = auto.ButtonControl(searchFromControl=window, Name="确定")
        if not confirm.Exists():
            return False
        self._human_click(confirm)
        return "已发送好友申请"

    def _click_cancel_button(self):
        """点击取消按钮"""
        self._log("取消按钮（空实现，没有点的）")